package com.lihepeng.leecode.juc;

/**
 * 生产者消费者 案例2
 * 使用blocking queue 来 保证生产一个消费一个
 */

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 蛋糕资源类
 */
class Cake {
    // 默认为开启状态表示生产者 消费
    private volatile boolean FLAG = true;
    private AtomicInteger atomicInteger = new AtomicInteger();

    private BlockingQueue<String> blockingQueue;

    public Cake(BlockingQueue blockingQueue) {
        this.blockingQueue = blockingQueue;
        System.out.println(blockingQueue.getClass().getName());
    }
    public void product() throws InterruptedException {
        String data ="";
        boolean result = false;
        while (FLAG) {
            data = atomicInteger.incrementAndGet()+"";

            result = blockingQueue.offer(data,2L, TimeUnit.SECONDS);
            Thread.sleep(1000);
            if (result) {
                System.out.println(Thread.currentThread().getName()+"向阻塞队列中添加数据成功，关联的数据为："+data);
            }else {
                System.out.println(Thread.currentThread().getName()+ "向阻塞队列中添加数据成功，关联的数据为"+data);
            }

        }
        TimeUnit.SECONDS.sleep(1);
        System.out.println("停止生产表示 当前FALG=false");

    }
    public void consumer () throws InterruptedException {
        while (FLAG) {
            String poll = blockingQueue.poll(2, TimeUnit.SECONDS);
            Thread.sleep(1000);
            if (poll ==null || "".equals(poll)) {
                FLAG = false;
                System.out.println(Thread.currentThread().getName() + "消费失败，当前队列中的数据为空");
                return;
            }
            System.out.println(Thread.currentThread().getName() +"消费："+poll+"成功");
        }

    }
    public void stop() {
        this.FLAG = false;
    }
}
public class ProductConsumerDemo2 {
    public static void main(String[] args) throws InterruptedException {
        Cake cake = new Cake(new ArrayBlockingQueue(3));
        new Thread(()->{
            try {
                cake.product();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"product").start();
        new Thread(()->{
            try {
                cake.consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"consumer").start();
        Thread.sleep(5000);
        cake.stop();
    }

}
